package com.dnzx.controller.system;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.dnzx.framework.result.ResultUtils;
import org.dnzx.framework.result.domain.Result;
import org.dnzx.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.dnzx.auth.AuthenticatService;
import com.dnzx.client.IRoleClient;
import com.dnzx.client.IUserClient;
import com.dnzx.model.system.RoleBO;
import com.dnzx.model.system.UserBO;
import com.dnzx.service.IParamService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @author 
 * @version V1.0
 * @date
 */
@RestController
@RequestMapping("/auth")
@Api(value = "/auth", description = "认证接口", produces = MediaType.APPLICATION_JSON_VALUE)
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private IUserClient userClient;
    @Autowired
    private IRoleClient roleClient;
    @Autowired
    private IParamService paramService;
//    @Autowired
//    private ISmsClient smsClient;
    @Autowired
    private AuthenticatService authenticatService;
//    @Autowired
//	private IMemberService memberService;
    
//    /**
//     * 
//     * 用户登录
//     */
//    @PostMapping(value = "/login")
//    @ApiOperation(value = "/login", notes = "用户登录(mobile和password)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
//    public Result login(@RequestBody UserBO userBO, HttpServletRequest request) {
//        try {
//        	// 查找用户信息，判断是否后台用户
//        	UserBO userBODb = this.userClient.get(userBO);
//        	if (userBODb == null) {
//        		throw new Exception("该用户不存在");
//        	}
//        	RoleBO roleBO = this.roleClient.get(userBODb.getRoleId());
//        	if (roleBO == null || !"0".equals(roleBO.getIsAdmin())) {// 不是前台用户
//        		throw new Exception("该用户不存在");
//        	}
//            String token = authenticatService.login(userBO.getMobile(), userBO.getPassword());
//            userBO = this.userClient.get(userBO);
//            userBO.setToken(token);
//            return ResultUtils.returnSuccess("SUCCESS", userBO);
//        } catch (Exception e) {
//            return ResultUtils.returnError("ERROR >>> "+ e.getMessage());
//        }
//
//    }
    
    /**
     * 
     * 后台用户登录
     */
    @PostMapping(value = "/adminLogin")
    @ApiOperation(value = "/adminLogin", notes = "用户登录(mobile和password)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public Result adminLogin(@RequestBody UserBO userBO, HttpServletRequest request) {
    	String langCode = request.getHeader("langCode");
        try {
        	// 查找用户信息，判断是否后台用户
        	UserBO userBODb = this.userClient.get(userBO);
        	String message = this.paramService.get("UNKNOWN_USER_" + langCode);// 该用户不存在
        	if (userBODb == null) {
        		throw new Exception(message);
        	}
        	RoleBO roleBO = this.roleClient.get(userBODb.getRoleId());
        	if (roleBO == null || !"1".equals(roleBO.getIsAdmin())) {// 不是后台用户
        		throw new Exception(message);
        	}
            String token = authenticatService.login(userBO.getMobile(), userBO.getPassword());
            userBO = this.userClient.get(userBO);
            userBO.setToken(token);
            return ResultUtils.returnSuccess("SUCCESS", userBO);
        } catch (Exception e) {
            if ("账户或密码错误".equals(e.getMessage()) && "en".equals(langCode)) {
        		return ResultUtils.returnError("Wrong account or password.");
        	} else {
        		return ResultUtils.returnError(e.getMessage());
        	}
        }

    }
    
//    /**
//     * 
//     * 发送短信验证码
//     */
//    @GetMapping(value = "/sendSms/{mobile}")
//    @ApiOperation(value = "/sendSms/{mobile}", notes = "发送忘记密码的短信验证码", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
//    public Result sendSms(@ApiParam(value = "mobile") @PathVariable("mobile") String mobile) {
//        try {
//        	UserBO userBO = new UserBO();
//        	userBO.setMobile(mobile);
//        	userBO = this.userClient.get(userBO);
//        	if (userBO == null ) {
//        		throw new Exception("手机号不存在");
//        	}
//        	SmsBO smsBO = new SmsBO();
//        	smsBO.setMobile(mobile);
//        	Random random = new Random();
//            int code = random.nextInt(99999) + 100000;
//        	String templateParam = "{'code':'" + code + "', 'minutes':'2'}";
//        	String templateCode = "SMS_102055004";
//        	smsBO.setUserId(userBO.getId());
//        	smsBO.setCode(String.valueOf(code));
//        	smsBO.setTemplateCode(templateCode);
//        	smsBO.setTemplateParam(templateParam);
//        	smsBO.setContent(templateParam);
//        	this.smsClient.save(smsBO);
//            return ResultUtils.returnSuccess("SUCCESS");
//        } catch (Exception e) {
//            return ResultUtils.returnError("ERROR >>> "+ e.getMessage());
//        }
//    }
    
//    /**
//     * 
//     * 发送短信验证码
//     */
//    @GetMapping(value = "/sendRegisterSms/{mobile}")
//    @ApiOperation(value = "/sendRegisterSms/{mobile}", notes = "发送注册的短信验证码", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
//    public Result sendRegisterSms(@ApiParam(value = "mobile") @PathVariable("mobile") String mobile) {
//        try {
//        	UserBO userBO = new UserBO();
//        	userBO.setMobile(mobile);
//        	userBO = this.userClient.get(userBO);
//        	if (userBO != null ) {
//        		throw new Exception("该手机号已经注册");
//        	}
//        	SmsBO smsBO = new SmsBO();
//        	smsBO.setMobile(mobile);
//        	Random random = new Random();
//            int code = random.nextInt(99999) + 100000;
//        	String templateParam = "{'code':'" + code + "', 'minutes':'2'}";
//        	String templateCode = "SMS_102055004";
//        	smsBO.setUserId(0L);// TODO 
//        	smsBO.setCode(String.valueOf(code));
//        	smsBO.setTemplateCode(templateCode);
//        	smsBO.setTemplateParam(templateParam);
//        	smsBO.setContent(templateParam);
//        	this.smsClient.save(smsBO);
//            return ResultUtils.returnSuccess("SUCCESS");
//        } catch (Exception e) {
//            return ResultUtils.returnError("ERROR >>> "+ e.getMessage());
//        }
//    }
    
    /**
     * 修改密码（忘记密码中的确认按钮）
     * @param user
     * @param request
     * @return
     */
    @PutMapping(value = "/forgetPwd")
    @ApiOperation(value = "/forgetPwd", notes = "修改密码：mobile、code、password，不需要传确认密码", httpMethod = "PUT", produces = MediaType.APPLICATION_JSON_VALUE)
    public Result forgetPwd(@RequestBody UserBO userBO) {
        try {
            this.userClient.forgetPwd(userBO);
            return ResultUtils.returnSuccess("SUCCESS");
        } catch (Exception e) {
        	e.printStackTrace();
            return ResultUtils.returnError("ERROR >>> " + e.getMessage());
        }
    }
   
    public static void main (String[] args) {
    	Date date = new Date(1576036523);
    	String dateStr = DateUtil.formatDate(date, "yyyy-MM-dd hh:mm:ss");
    	System.out.println(dateStr);
    }

}	

